package com.tvunetworks.center.user.util;

import lombok.extern.slf4j.Slf4j;
import net.spy.memcached.MemcachedClient;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @program: tvucc-aggregator
 * @description: MemcacheUtil
 * @author lebronchen
 * @create: 2020-04-21 14:28
 **/
@Component
@Slf4j
public class MemcacheUtil {

    @Value("${memcache.multiGetNum}")
    private int multiGetNum;

    /**
     *
     * @param memcachedClient memcachedClient
     * @param keys keys
     * @return Map
     */
    public Map<String, Object> multiGet(MemcachedClient memcachedClient, Collection<String> keys){
        if (CollectionUtils.isEmpty(keys)) {
            return null;
        }
        List<String> list = new ArrayList<>(keys);
        Map<String, Object> result = new HashedMap();
        int size = list.size();

        int start = 0;
        int end = multiGetNum;

        while (true) {
            if (end > size) {
                end = size;
            }
            Map<String, Object> map = memcachedClient.getBulk(list.subList(start, end));
            if (!CollectionUtils.isEmpty(map)) {
                result.putAll(map);
            }
            if (end == size) {
                break;
            }
            start = end;
            end += multiGetNum;
        }
        return result;
    }


}
